package com.ny.dao.impl;

import com.ny.dao.OrderDao;
import com.ny.entity.Order;
import com.ny.until.DbUntil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class OrderDaoImpl implements OrderDao {
    private  DbUntil dbUntil = new DbUntil();

    @Override
    public int insertOrder(Order order) throws Exception, ClassNotFoundException {
        Connection connection = dbUntil.getCon();
        String sql = "insert into orders(student_id,product_id,number,total_price)values(?,?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, order.getStudentId());
        preparedStatement.setInt(2, order.getProductId());
        preparedStatement.setInt(3, order.getNumber());
        preparedStatement.setDouble(4, order.getPrice());
        return preparedStatement.executeUpdate();
    }

    @Override
    public List<Order> getAllOrders() throws Exception {
        Connection connection = dbUntil.getCon();
        String sql = "select * from orders";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        List<Order> orderList = new ArrayList<>();
        while (resultSet.next()) {
            Order order = new Order();
            order.setOrderId(resultSet.getInt("order_id"));
            order.setStudentId(resultSet.getInt("student_id"));
            order.setProductId(resultSet.getInt("product_id"));
            order.setNumber(resultSet.getInt("number"));
            order.setPrice(resultSet.getDouble("total_price"));
            orderList.add(order);

        }
        return orderList;

    }

    @Override
    public Order getOrderById(int id) throws Exception {
        Connection connection = dbUntil.getCon();
        String sql = "select * from orders where order_id=?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, id);
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            Order order = new Order();
            order.setOrderId(resultSet.getInt("order_id"));
            order.setStudentId(resultSet.getInt("student_id"));
            order.setProductId(resultSet.getInt("product_id"));
            order.setNumber(resultSet.getInt("number"));
            order.setPrice(resultSet.getDouble("total_price"));
            return order;
        }
        return null;
    }

    @Override
    public int deleteOrder(int id) throws Exception {
        Connection connection = dbUntil.getCon();
        String sql = "delete from orders where order_id=?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, id);
        return preparedStatement.executeUpdate();
    }
}
